import { _decorator, Button, find, instantiate, Label, NodePool, ProgressBar, RichText, Sprite, SpriteAtlas, SpriteFrame, tween, Tween, UITransform, v3, Widget } from 'cc';
import { $planet_BaseUI_poof$ } from '../../../frame/component/ui.base';
import { $planet_PLANET_SPRITE_poof$ } from '../../config.global';
import { $planet_ClientAPI_poof$ } from '../api/client.api';
import $planet_ServiceAPI_poof$ from '../api/service.api';
import $planet_DC_poof$ from '../data/data.center';
import $planet_Config_poof$ from '../manager/config.dynamic';
import $planet_GameAssets_poof$ from '../manager/game-assets';
import { $planet_Float_poof$ } from './float';
import { $planet_Pop_poof$ } from './pop';
const { ccclass, property } = _decorator;

@ccclass('$planet_HomeUI_poof$')
export class $planet_HomeUI_poof$ extends $planet_BaseUI_poof$ {
	@property(SpriteAtlas)
	private planet_atlas: SpriteAtlas = null;

	private ui_top: UITransform;
	private ui_bottom: UITransform;

	private va_top: abd.$planet_cc_poof$.$planet_VecAssist_poof$;
	private va_bottom: abd.$planet_cc_poof$.$planet_VecAssist_poof$;
	private $planet_sprite_planet_map_poof$: Map<string, SpriteFrame>;

	protected $planet_initAfterOnLoad_poof$(): void {
		[this.ui_top, this.ui_bottom] = ['top', 'bottom'].map(name=>this.node.getChildByName(name).getComponent(UITransform));
		[this.va_top, this.va_bottom] = [this.ui_top, this.ui_bottom].map(ui=>new abd.$planet_cc_poof$.$planet_VecAssist_poof$(ui.node));
		this.$planet_sprite_planet_map_poof$ = new Map(this.planet_atlas.getSpriteFrames().map(sframe=>[sframe.name, sframe]));
	}

	protected start(): void {
		this.$planet_init_poof$();
	}

	private $planet_init_poof$(){
		this.ui_top.node.setPosition(this.va_top.$planet_getPosition_poof$('$planet_center_poof$', '$planet_over_top_poof$'));
		this.ui_bottom.node.setPosition(this.va_bottom.$planet_getPosition_poof$('$planet_center_poof$', '$planet_over_bottom_poof$'));

		this.node.active = false;

		let wgt = this.node.getComponent(Widget);
		if(wgt) wgt.updateAlignment();
		this.$planet_renderLocalUI_poof$();
	}

	protected $planet_listening_poof$(){
		let [lbl_symbol, lbl_elsb, lbl_elsbcount] = ['symbol', 'elsb', 'elsb-count'].map(name=>this.ui_top.node.getChildByName('lbl-'+name).getComponent(Label));
		let [lbl_desc, lbl_progress] = ['desc', 'progress'].map(name=>this.ui_bottom.node.getChildByName('lbl-'+name).getComponent(Label));
		let progress_score = this.ui_bottom.node.getChildByName('progress').getComponent(ProgressBar);
		let icon_symbol = find('symbol/icon', this.ui_top.node);
		let icon_elsb_statistics = find('elsb-statistics/icon', this.ui_top.node).getComponent(Sprite);

		let node_bubble = this.ui_top.node.getChildByName('bubble');
		let lbl_bubble = this.ui_top.node.getChildByName('lbl-bubble').getComponent(RichText);
		let first_free = $planet_Config_poof$.$planet_otherConfig_poof$.$planet_freeSymbol_poof$.sort((a, b)=>a.$planet_symbol_poof$-b.$planet_symbol_poof$)[0];
		let [pos_node_bubble, pos_lbl_bubble] = [node_bubble, lbl_bubble.node].map(n=>n.position.clone());
		let [pos_node_bubble_end, pos_lbl_bubble_end] = [pos_node_bubble, pos_lbl_bubble].map(v=>v.clone().add3f(0, 20, 0));

		(<const>[
			[node_bubble, pos_node_bubble, pos_node_bubble_end],
			[lbl_bubble.node, pos_lbl_bubble, pos_lbl_bubble_end]
		]).forEach(([node, pos, pos_end])=>{
			Tween.stopAllByTarget(node);
			tween(node)
			.to(0.4, {position: pos_end})
			.to(0.4, {position: pos})
			.union().repeat(3).delay(0.8)
			.union().repeatForever()
			.start();
		});

		let list = [];

		let wait_rp = false;

		let lbl_symbol_pool = new NodePool();

		Promise.all([
			$planet_DC_poof$.$planet_follow_poof$('$planet_trigger_poof$', '$planet_UI_HOME_poof$', (o, show)=>{
				if(show===o) return void 0;
				show ? this.$planet_enter_poof$() : this.$planet_leave_poof$();
			}, false),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_symbol_poof$', (_, v)=>{

				let first = v < first_free.$planet_symbol_poof$;
				node_bubble.active = first;
				lbl_bubble.node.active = first;
				if(first){
					let diff = $planet_DC_poof$.$planet_symbolString_poof$(first_free.$planet_symbol_poof$-v);
					let target = $planet_DC_poof$.$planet_symbolString_poof$(first_free.$planet_symbol_poof$);

					[diff, target] = [diff, target].map(s=>'<color=#DF4C53>'+s+'</color>');
					lbl_bubble.string = $planet_GameAssets_poof$.$planet_getLangText_poof$(1, diff, target);
				}else [node_bubble, lbl_bubble.node].forEach(n=>Tween.stopAllByTarget(n));

				if(wait_rp) return void 0;
				let value = v??$planet_DC_poof$.$planet_user_poof$.$planet_symbol_poof$;
				lbl_symbol.string = $planet_DC_poof$.$planet_symbolString_poof$(value);

				if(_){
					let diff = value - _;
					let lbl: Label;
					if(lbl_symbol_pool.size() > 0) lbl = lbl_symbol_pool.get().getComponent(Label);
					else lbl = instantiate(lbl_symbol.node).getComponent(Label);
					lbl.node.active = false;
					lbl.string = '+' + $planet_DC_poof$.$planet_symbolString_poof$(diff);
					lbl.node.setParent(lbl_symbol.node.parent);
					lbl.node.setPosition(lbl_symbol.node.position);
					lbl.node.scale.set(0.8, 0.8, 1);
					lbl.node.position.add3f(0, 20, 0);

					lbl.node.active = true;

					tween(lbl.node)
					.by(0.6, {position: v3(0, 35, 0)})
					.delay(0.6).call(()=>lbl_symbol_pool.put(lbl.node)).start();
				}
			}),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_elsb_poof$', (_, v)=>{
				lbl_elsb.string = String(v??$planet_DC_poof$.$planet_user_poof$.$planet_elsb_poof$);
			}),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_count_elsb_poof$', (_, v)=>{
				lbl_elsbcount.string = $planet_GameAssets_poof$.$planet_getLangText_poof$(2, v??$planet_DC_poof$.$planet_user_poof$.$planet_count_elsb_poof$);
			}),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_score_poof$', (_, v)=>{
				let target = $planet_DC_poof$.$planet_user_poof$.$planet_score_target_poof$;
				let score = Math.min(v??$planet_DC_poof$.$planet_user_poof$.$planet_score_poof$, target);
				lbl_progress.string = `${score} / ${target}`;
				let progress = score / target;
				let diff = Math.abs(progress-progress_score.progress);

				if(diff>0){
					Tween.stopAllByTarget(progress_score);
					tween(progress_score).to(diff*1, {progress: $planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$}, {easing: 'quadOut'}).start();
				}

				if(progress>=1){
					lbl_desc.string = $planet_GameAssets_poof$.$planet_getLangText_poof$(13);
					if(diff>0){
						$planet_Float_poof$.$planet_pointerTo_poof$(this.$planet___btn_map___poof$.get('gift').node);
					}
				}else{
					$planet_Float_poof$.$planet_hidePointer_poof$();
					lbl_desc.string = $planet_GameAssets_poof$.$planet_getLangText_poof$(12, target-score);
				}
			}),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_score_target_poof$', (_, v)=>{
				let target = v??$planet_DC_poof$.$planet_user_poof$.$planet_score_target_poof$;
				lbl_progress.string = `${Math.min($planet_DC_poof$.$planet_user_poof$.$planet_score_poof$, target)} / ${target}`;

				let progress = $planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$
				let diff = Math.abs(progress-progress_score.progress);
				if(diff<=0) return void 0;

				if(progress>=1) $planet_Float_poof$.$planet_pointerTo_poof$(this.$planet___btn_map___poof$.get('gift').node);
				else $planet_Float_poof$.$planet_hidePointer_poof$();
				Tween.stopAllByTarget(progress_score);
				tween(progress_score).to(diff * 1, {progress: $planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$}, {easing: 'quadOut'}).start();
			}),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_fusionCount_poof$', async (_, v)=>{
				// Red Packet(红包)
				let rp = v!=_ && (v%3==0);
				if(!rp) return void 0;

				$planet_DC_poof$.$planet_user_poof$.$planet_rp_count_poof$++;
				let ad_type = $planet_DC_poof$.$planet_checkForcePop_poof$();
				if(ad_type){
					let success = await $planet_ClientAPI_poof$.$planet_AD_poof$(ad_type);
					if(success) $planet_DC_poof$.$planet_status_poof$.$planet_videoCount_poof$++;
				}
				$planet_DC_poof$.$planet_status_poof$.$planet_has_force_poof$ = false;
				let result = await $planet_ServiceAPI_poof$.$planet_fruitGet_poof$(ad_type ? 2 : 0);
				wait_rp = true;
				$planet_DC_poof$.$planet_user_poof$.$planet_symbol_poof$ = (await $planet_ServiceAPI_poof$.$planet_fruitConfirm_poof$(result.$planet_logId_poof$)).$planet_symbol_poof$;
				await $planet_DC_poof$.$planet_synchUserInfo_poof$();
				$planet_ClientAPI_poof$.$planet_Fruit_poof$(ad_type ? 2 : 0);

				await $planet_Float_poof$.$planet_Congratulation_poof$(result.$planet_fruit_poof$, $planet_GameAssets_poof$.$planet_getLangText_poof$(ad_type ? 4 : 3));
				await $planet_Float_poof$.$planet_Reap_poof$(icon_symbol, abd.$planet_number_poof$.$planet_random_poof$(6, 8), abd.$planet_cc_poof$.$planet_canvas_poof$.node.position);
				lbl_symbol.string = $planet_DC_poof$.$planet_symbolString_poof$($planet_DC_poof$.$planet_user_poof$.$planet_symbol_poof$);

				let lbl: Label;
				if(lbl_symbol_pool.size() > 0) lbl = lbl_symbol_pool.get().getComponent(Label);
				else lbl = instantiate(lbl_symbol.node).getComponent(Label);
				lbl.node.active = false;
				lbl.string = '+' + $planet_DC_poof$.$planet_symbolString_poof$(result.$planet_fruit_poof$);
				lbl.node.setParent(lbl_symbol.node.parent);
				lbl.node.setPosition(lbl_symbol.node.position);
				lbl.node.scale.set(0.8, 0.8, 1);
				lbl.node.position.add3f(0, 20, 0);

				lbl.node.active = true;

				tween(lbl.node)
				.by(0.6, {position: v3(0, 35, 0)})
				.delay(0.6).call(()=>lbl_symbol_pool.put(lbl.node)).start();

				wait_rp = false;
			}, false),
			$planet_DC_poof$.$planet_follow_poof$('$planet_trigger_poof$', '$planet_NEW_ELSB_poof$', (_, id)=>{
				$planet_Float_poof$.$planet_moveElsb_poof$(icon_elsb_statistics.node)
				.then(()=>{
					$planet_Float_poof$.$planet_destroyElsb_poof$();
					$planet_DC_poof$.$planet_user_poof$.$planet_count_elsb_poof$++;
					$planet_DC_poof$.$planet_user_poof$.$planet_elsb_poof$++;
					$planet_Pop_poof$.$planet_Elsb_poof$();
				});
			}, false),
			$planet_DC_poof$.$planet_follow_poof$('$planet_trigger_poof$', '$planet_RESET_poof$', (o, v)=>{
				if(v==o || v) return void 0;
				this.$planet___btn_map___poof$.get('reset').interactable = true
			}, false),
			$planet_DC_poof$.$planet_follow_poof$('$planet_user_poof$', '$planet_target_planet_poof$', (_, id)=>{
				let sframe = this.$planet_sprite_planet_map_poof$.get($planet_PLANET_SPRITE_poof$[id]);
				if(sframe){
					abd.$planet_cc_poof$.$planet_skinPeeler_poof$(icon_elsb_statistics.node, sframe, {height: true});
				}
			}),
		]).then(ls=>list.push(...ls));

		return list;
	}

	protected $planet__click_event__poof$: { [name: string]: (this: $planet_HomeUI_poof$, button: Button) => void; } = {
		free(btn){
			btn.interactable = false;
			$planet_DC_poof$.$planet_trigger_poof$.$planet_UI_HOME_poof$ = false;
			$planet_DC_poof$.$planet_trigger_poof$.$planet_UI_FREE_poof$ = 'symbol';
		},
		convert(btn){
			btn.interactable = false;
			$planet_DC_poof$.$planet_trigger_poof$.$planet_UI_HOME_poof$ = false;
			$planet_DC_poof$.$planet_trigger_poof$.$planet_UI_FREE_poof$ = 'elsb';
		},
		setting(btn){
			$planet_ClientAPI_poof$.$planet_Link_poof$($planet_Config_poof$.$planet_otherConfig_poof$.$planet_privacy_poof$);
			//btn.interactable = false;
			//$planet_Pop_poof$.$planet_Setting_poof$().then(()=>btn.interactable = true);
		},
		async gift(btn){
			btn.interactable = false;
			$planet_Float_poof$.$planet_hidePointer_poof$();
			if($planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$<1){
				let diff = $planet_DC_poof$.$planet_user_poof$.$planet_score_target_poof$ - $planet_DC_poof$.$planet_user_poof$.$planet_score_poof$
				await $planet_Float_poof$.$planet_Hint_poof$($planet_GameAssets_poof$.$planet_getLangText_poof$(12, diff));
			}else{
				let result = await $planet_Pop_poof$.$planet_Gift_poof$();
				let symbol = (await $planet_ServiceAPI_poof$.$planet_giftConfirm_poof$(result.$planet_logId_poof$)).$planet_symbol_poof$;
				let next_target_score = $planet_DC_poof$.$planet_getNextTargetScore_poof$();
				await $planet_Pop_poof$.$planet_Fruit_poof$(result.$planet_value_poof$, next_target_score-$planet_DC_poof$.$planet_user_poof$.$planet_score_poof$);
				await $planet_Float_poof$.$planet_Reap_poof$(find('symbol/icon', this.ui_top.node), abd.$planet_number_poof$.$planet_random_poof$(6, 8), abd.$planet_cc_poof$.$planet_canvas_poof$.node.position);
				$planet_DC_poof$.$planet_user_poof$.$planet_symbol_poof$ = symbol;
				$planet_DC_poof$.$planet_user_poof$.$planet_score_target_poof$ = next_target_score;
			}

			if($planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$>=1) $planet_Float_poof$.$planet_pointerTo_poof$(btn.node);

			btn.interactable = true;
		},
		reset(btn){
			btn.interactable = false;
			$planet_DC_poof$.$planet_trigger_poof$.$planet_RESET_poof$ = true;
		}
	}

	private $planet_enterBefore_poof$(){
		['free', 'convert'].forEach(name=>this.$planet___btn_map___poof$.get(name).interactable = true);
	}

	private $planet_enterAfter_poof$(){
		if($planet_DC_poof$.$planet_user_poof$.$planet_score_progress_poof$>=1) $planet_Float_poof$.$planet_pointerTo_poof$(this.$planet___btn_map___poof$.get('gift').node);
		else $planet_Float_poof$.$planet_hidePointer_poof$();
	}

	private $planet_enter_poof$(){
		this.$planet_enterBefore_poof$();
		let duration = 0.5;
		let np = new abd.$planet_NudityPromise_poof$<0>();
		this.node.active = true;
		this.scheduleOnce(()=>np.$planet_resolve_poof$(0), duration+0.05);

		this.va_top.$planet_getPosition_poof$('$planet_center_poof$', '$planet_top_poof$');
		this.va_bottom.$planet_getPosition_poof$('$planet_center_poof$', '$planet_bottom_poof$');
		if(abd.$planet_cc_poof$.$planet_is_long_screen_poof$) this.va_top.$planet_vec_poof$.add3f(0, -100, 0);

		(<const>[
			[this.ui_top, this.va_top],
			[this.ui_bottom, this.va_bottom],
		]).forEach(([ui, va])=>{
			Tween.stopAllByTarget(ui.node);
			tween(ui.node).to(duration, {position: va.$planet_vec_poof$}, {easing: 'quartInOut'}).start();
		});

		np.$planet_promise_poof$.then(()=>this.$planet_enterAfter_poof$());

		return np.$planet_promise_poof$;
	}

	private $planet_leaveBefore_poof$(){
		$planet_Float_poof$.$planet_hidePointer_poof$();
	}

	private $planet_leave_poof$(){
		this.$planet_leaveBefore_poof$();
		let duration = 0.5;
		let np = new abd.$planet_NudityPromise_poof$<0>();
		this.scheduleOnce(()=>np.$planet_resolve_poof$(0), duration+0.05);

		this.va_top.$planet_getPosition_poof$('$planet_center_poof$', '$planet_over_top_poof$');
		this.va_bottom.$planet_getPosition_poof$('$planet_center_poof$', '$planet_over_bottom_poof$');

		(<const>[
			[this.ui_top, this.va_top],
			[this.ui_bottom, this.va_bottom],
		]).forEach(([ui, va])=>{
			Tween.stopAllByTarget(ui.node);
			tween(ui.node).to(duration, {position: va.$planet_vec_poof$}, {easing: 'quartInOut'}).start();
		});

		np.$planet_promise_poof$.then(()=>this.node.active = false);

		return np.$planet_promise_poof$;
	}

	/** 渲染本地UI */
	private $planet_renderLocalUI_poof$(){
		(<const>[
			['free', 7],
			['convert', 8],
		]).forEach(([name, id])=>{
			let sprite = this.$planet___btn_map___poof$.get(name).getComponent(Sprite);
			let sframe = $planet_GameAssets_poof$.$planet_getLangTexture_poof$(id);
			abd.$planet_cc_poof$.$planet_skinPeeler_poof$(sprite.node, sframe, {height: true});
		});

		abd.$planet_cc_poof$.$planet_skinPeeler_poof$(find('symbol/icon', this.ui_top.node), $planet_GameAssets_poof$.$planet_getCounTexture_poof$(0), {width: true});
	}

}

